package com.example.Controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.Service.DepartmentService;
import com.example.Service.PositionService;
import com.example.Service.impl.UserServiceImpl;
import com.example.dao.DepartmentMapper;
import com.example.dao.LeaveemployeeMapper;
import com.example.dao.UserMapper;
import com.example.exception.MyException;
import com.example.pojo.Department;
import com.example.pojo.Leaveemployee;
import com.example.pojo.Position;
import com.example.pojo.User;

import com.example.util.*;
import com.example.util.ThreadLocalUtil;
import com.example.util.sms.SmsUtils;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;


@Api(tags = "用户管理")
@CrossOrigin
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;




    @Autowired
    private LeaveemployeeMapper leaveemployeeMapper;

    @Autowired
    private UserServiceImpl userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private PositionService positionService;

    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private DepartmentService departmentService;


    @RequestMapping("/selectAllByDepartment")
    public Result selectAllByDepartment() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("department_id", "COUNT(*) as count");
        queryWrapper.groupBy("department_id");
        List<User> list = userMapper.selectList(queryWrapper);
        for (User user : list) {
            if (user.getDepartmentId() != null) {
                QueryWrapper<Department> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("department_id", user.getDepartmentId());
                Department department=departmentMapper.selectOne(queryWrapper1);
                user.setDepartmentName(department.getDepartmentName());
            }else {
                user.setDepartmentName("无部门");
            }
        }
        return new Result("200","获取部门数据",list);
    }
    @RequestMapping("/login")
    public Result login(@RequestBody User user){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",user.getId());
        User user1 = userMapper.selectOne(queryWrapper);
        String token = "";
        if (user1==null){
            throw new MyException("101","用户不存在");
        }
        //加盐
        String slat = user1.getPassword().split("\\$")[0];
        String encrypt = PasswordUtils.encrypt(MD5.encrypt(user.getPassword()),slat);

        if (!user1.getPassword().equals(encrypt)){
            throw new MyException("102","密码不正确");
        }

        token = UUID.randomUUID().toString();
        String json = JSONObject.toJSONString(user1);
        stringRedisTemplate.opsForValue().set(token,json,1, TimeUnit.HOURS);
        Long id = Long.valueOf(user1.getId());
        ThreadLocalUtil.setCurrentId(id);
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",user1);
        return new Result("200","登陆成功",map);
    }

    //重置用户密码
    @PutMapping("/updatePassword/{id}")
    public Result updatePassword(@PathVariable("id") Integer id) {
        userService.updatePassword(id);
        return new Result("200","修改成功");
    }

    //查询用户修改前的密码
    @GetMapping("/selectPassword/{id}")
    public Result selectPassword(@PathVariable("id") Integer id){
        User user = userService.selectPassword(id);
        if(user == null){
            return new Result("200","查询失败");
        }

        String salt=user.getPassword().split("\\$")[0];
        String finalPassword=PasswordUtils.encrypt(MD5.encrypt(user.getPassword()),salt);

        user.setPassword(finalPassword);
        return new Result("200","查询成功",user);
    }


    //判断用户确认的密码是否和原密码一致
    @GetMapping("/checkPassword")
    public Result checkPassword(@RequestParam(value = "id",required = false) Integer id,
                                @RequestParam(value = "password",required = false) String password){
        User user = userService.selectPassword(id);
        if(user == null){
            return new Result("200","查询失败");
        }

        String salt=user.getPassword().split("\\$")[0];

        String checkPassword= user.getPassword();
        String checkPasswordAgain= PasswordUtils.encrypt(MD5.encrypt(password),salt);

        if (!checkPassword.equals(checkPasswordAgain)){
            return new Result("200","原密码错误");
        }

        return new Result("200","密码正确");
    }

    //重置用户密码
    @PutMapping("/updateUserPassword")
    public Result updateUserPassword(@RequestBody User user){
        userService.updateUserPassword(user);
        return new Result("200","修改成功");
    }


    @GetMapping("/select")
    public Result<Map<String, Object>> getInfo(HttpServletRequest request) {
        Map<String, Object> data;
        try {
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token)) {
                return new Result<>("400", "缺少token参数");
            }

            String json = stringRedisTemplate.opsForValue().get(token);
            if (StringUtils.isEmpty(json)) {
                return new Result("401", "token无效或已过期");
            }

            User user = JSON.parseObject(json, User.class);
            if (user == null) {
                return new Result("500", "用户信息解析失败");
            }

            // 并行获取部门及职位信息
            // 创建一个CompletableFuture对象，异步获取用户所在部门的详细信息
            CompletableFuture<Department> departmentFuture = CompletableFuture.supplyAsync(() ->
                    departmentService.getById(user.getDepartmentId()));
            // 创建一个CompletableFuture对象，异步获取用户所在职位的详细信息
            CompletableFuture<Position> positionFuture = CompletableFuture.supplyAsync(() ->
                    positionService.getById(user.getPositionId()));

            // 等待两个CompletableFuture对象都完成
            CompletableFuture.allOf(departmentFuture, positionFuture).join();

            // 获取用户所在部门的详细信息
            Department department = departmentFuture.get();
            // 获取用户所在职位的详细信息
            Position position = positionFuture.get();

            // 如果department不为空，则将department的departmentName赋值给user的departmentName，否则将"未知部门"赋值给user的departmentName
            user.setDepartmentName(department != null ? department.getDepartmentName() : "未知部门");
            // 如果position不为空，则将position的positionName赋值给user的positionName，否则将"未知职位"赋值给user的positionName
            user.setPositionName(position != null ? position.getPositionName() : "未知职位");

            data = new HashMap<>();
            data.put("data", user);

        } catch (JSONException e) {
            return new Result("500", "数据解析异常", null);
        } catch (InterruptedException | ExecutionException e) {

            Thread.currentThread().interrupt();
            return new Result("500", "服务处理超时", null);
        } catch (Exception e) {
            return new Result("500", "系统繁忙", null);
        }
        return new Result("200", "查询成功", data);
    }


    /**
     * 生产部门  ---> 生产人员
     */
    @GetMapping("/selectAllPage")
    public Result selectAllProduct(User user, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "8") Integer pageSize){
        PageInfo<User> pageInfo = userService.selecAllProduct(user,pageNum,pageSize);
        return new Result("200","查询成功",pageInfo);
    }

    //添加生产部门信息
    @PostMapping("/addProduct")
    public Result addProduct(@RequestBody User user) {
        userService.addProduct(user);
        return new Result("200","添加成功");
    }

    //修改用户信息
    @PutMapping("/updateProduct")
    public Result updateProduct(@RequestBody User user){
        userService.updateProduct(user);
        return new Result("200","修改成功");
    }

    /**
     * it部门 ---> 全部it部门人员
     */
    @GetMapping("/selectAllItPage")
    public Result selectAllItPage(User user,@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize){
        PageInfo<User> pageInfo = userService.selectAllItPage(user,pageNum,pageSize);
        return new Result("200","查询成功",pageInfo);
    }

//    @GetMapping("sendCode")
//    public Result sendCode(String phone){
//        String code = MathUtils.random(); //生成验证码
//        System.out.println(code);
//        boolean bo = false;
//        try {
//            stringRedisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
//            bo = smsUtils.sendMessage(phone,code); // 发送验证码
//        }catch (Exception e){
//            bo = false;
//            throw new RuntimeException(e);
//        }
//        if (!bo){
//            return new Result("300","短信发送失败");
//        }
//        return new Result("200","短信发送成功");
//    }
//


     @GetMapping("/selectAll") //员工的信息查询
     public Result getUsers(@RequestParam(value = "name",defaultValue ="")String name,
                            @RequestParam(value = "id",defaultValue ="")Integer id,
                            @RequestParam(value = "departmentId",defaultValue ="")Integer departmentId,
                            @RequestParam(value = "positionId",defaultValue ="")Integer positionId,
                            @RequestParam(value = "PageNum",defaultValue ="1")Integer PageNum,
                            @RequestParam(value = "PageSize",defaultValue ="14")Integer PageSize){
         PageInfo<User> users = userService.selectAll(name, id, departmentId, positionId, PageNum, PageSize);

         return new Result("200", "查询成功",users);
    }

    @PostMapping("/registerAccount") //人事添加  //注册
    public Result resgist(@RequestBody User user){
        //MD5加密
        LocalDateTime dateTime = LocalDateTime.now();  //当天时间


        if (user!=null){
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("name",user.getName());
            User user1 = userMapper.selectOne(userQueryWrapper); //查询用户
            if (user1!=null){
                return  new Result("200","查询成功");
            }

            user.setCreateDate(dateTime);
            user.setPassword(PasswordUtils.encrypt(MD5.encrypt(user.getPassword())));
            int rows = userMapper.insert(user);
            if (rows>0){
                return new Result("200","注册成功");
            }
            return new Result("202","注册失败");
        }
        return new Result("203","注册失败");
    }

    @RequestMapping("/selectOne") //通过id查询用户信息
    public  Result selectOne(Integer id){
        User user = userService.selectOne(id);
        return new Result("200","查询成功",user);
    }


    @RequestMapping("/updateUserInfo") //修改用户信息
    public  Result updateUserInfo(@RequestBody User user){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",user.getId());
        int update = userMapper.update(user, wrapper);
        return new Result("200","修改成功",update);
    }

    @RequestMapping("/deleteUser") //删除用户信息  //辞退
    public  Result deleteUser(Integer id){
        LocalDateTime localDateTime = LocalDateTime.now();


        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);

        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("id",id);



        User user = userMapper.selectOne(id);

        System.out.println(user);
        int delete = userMapper.delete(wrapper);
        Leaveemployee leaveemployee = new Leaveemployee();

        leaveemployee.setName(user.getName());
        leaveemployee.setDepartmentId(user.getDepartmentId());
        leaveemployee.setPositionId(user.getPositionId());
        leaveemployee.setSex(Integer.valueOf(user.getSex()));
        leaveemployee.setStatus(1);
        leaveemployee.setLeaveDate(localDateTime);

        if (delete>0){
             int insert = leaveemployeeMapper.insert(leaveemployee);
            if(insert>0){
                return new Result("200","删除成功",delete);
            }

        }
        return new Result("406","删除失败",delete);
    }


    @RequestMapping("/JumpInfo")  //查询名字
    public  Result  JumpInfo(@RequestParam(value = "name",defaultValue = "") String name){
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("name",name);
        User user1 = userMapper.selectOne(wrapper);
        if (user1.getPositionId()<3){
            return  new Result("200","查询成功","权限不足");
        }
        User user = userService.selectJump(name);
        return  new Result("200","查询成功",user);
    }


    @RequestMapping("updateUserDepart")  //修改用户部门   //bug
    public  Result updateUserDepart(@RequestBody User user){
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println(user);
        User user1 = new User();
        user1.setCreateDate(dateTime);
        user1.setDepartmentId(user.getDepartmentId());
        user1.setPositionId(user.getPositionId());
        System.out.println(user.getCreateDate());
        user1.setCreateDate(user.getCreateDate());
        user1.setCreateBy(user.getCreateBy());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name",user.getName());
        int update = userMapper.update(user1,wrapper);
        return new Result("200","修改成功",update);
    }





    @GetMapping("/realNameAuthentication")
    public Result realNameAuthentication(@RequestParam(value = "id",required = false) String id){
        User user = userService.realNameAuthentication(id);
        return new Result("200","实名认证成功",user);
    }

    @PutMapping("/edit")
    public  Object updateInfo(@RequestBody User user){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",user.getId());
        int bo = userMapper.update(user,queryWrapper);
        if (bo>0){
            return new Result<>("200","修改成功",null);
        }
        return new Result<>("500","修改失败",null);
    }

//    @PutMapping("updatePassword")
//    public Object updatePassword(@RequestParam("password1") String password1,@RequestParam("password2") String password2,@RequestParam("id") Integer id){
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("id",id);
//        User user = userMapper.selectOne(queryWrapper);
//        if (user.getPassword().equals(password1)){
//            user.setPassword(password2);
//        }else{
//            return new Result<>("500","密码错误",null);
//        }
//        int bo = userMapper.update(user,queryWrapper);
//        if (bo>0){
//            return new Result<>("200","修改成功",null);
//        }
//        return new Result<>("500","修改失败",null);
//    }



    @PutMapping("reallyName")
    public  Object ReallyName(@RequestParam("name")String name ,
                              @RequestParam("idCard")String idCard){

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1==null){
            return new Result<>("400","用户不存在",null);
        }
        user1.setName(name);
        user1.setIdCard(idCard);
        int bo = userMapper.update(user1,queryWrapper);
        if (bo>0){
            return new Result<>("200","实名验证成功",null);
        }
        return new Result<>("400","用户不存在",null);
    }


//
//    @PostMapping("updateAvatar")
//    @Transactional  // 添加事务管理
//    public Result<String> updateAvatar(
//            @RequestParam("imageUrl") String imageUrl,
//            HttpServletRequest request) {
//
//        // 1. 校验 Token
//        String token = request.getHeader("token");
//        if (token == null || token.isEmpty()) {
//            return new Result<>("401", "未登录", null);
//        }
//
//        // 2. 从 Redis 获取用户数据
//        String json = stringRedisTemplate.opsForValue().get(token);
//        if (json == null || json.isEmpty()) {
//            return new Result<>("401", "登录已过期，请重新登录", null);
//        }
//
//        try {
//            // 3. 解析 JSON 并校验关键字段
//            User user = JSON.parseObject(json, User.class);
//            if (user.getId() == null) {
//                return new Result<>("500", "用户数据异常", null);
//            }
//
//
//            // 4. 创建更新对象，仅修改头像字段
//            User updateUser = new User();
//            updateUser.setId(user.getId()); // 确保更新条件
//            updateUser.setImgUrl(imageUrl);
//
//            // 5. 直接按 ID 更新头像，避免全字段更新
//            int rows = userMapper.updateById(updateUser);
//            if (rows > 0) {
//                return new Result<>("200", "头像更新成功", null);
//            } else {
//                return new Result<>("500", "头像更新失败", null);
//            }
//
//        } catch (Exception e) {
//            // 7. 捕获 JSON 解析等异常
//            return new Result<>("500", "服务器内部错误: " + e.getMessage(), null);
//        }
//    }

}
